package com.hyf.gateway.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author baB_hyf
 * @date 2021/07/14
 */
public class EncodeUtils {

    public static final String ALGORITHM_SHA256 = "SHA-256";

    public static String sha256(String str) {
        try {
            MessageDigest messageDigest;
            messageDigest = MessageDigest.getInstance(ALGORITHM_SHA256);
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            return byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 encrypt fail", e);
        }
    }

    // byte转换成16进制
    public static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString();
    }
}
